package com.linkoog.devtools.json.file_editer.editer.toolbar;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.linkoog.devtools.utils.formatter.JsonFormatter;
import org.jetbrains.annotations.NotNull;

public class JsonPrettyAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) return;
        Editor editor = e.getData(LangDataKeys.EDITOR);
        if (editor == null)  return;

        Document document = editor.getDocument();
        CommandProcessor.getInstance().executeCommand(
            project,
            () -> ApplicationManager.getApplication().runWriteAction(() -> {
                try {
                    String context = document.getCharsSequence().toString();
                    String pretty = JsonFormatter.pretty(context);
                    document.setText(pretty);
                }catch (Exception ignore){
                }
            }),
            null,
            null,
            UndoConfirmationPolicy.DEFAULT,
            document
        );
    }
}
